package com.cheetah.service.impl;

import com.cheetah.dao.GroupDAO;
import com.cheetah.dto.GroupDTO;
import com.cheetah.entity.Group;
import com.cheetah.entity.Message;
import com.cheetah.exceptions.CheetahRuntimeException;
import com.cheetah.exceptions.ServerError;
import com.cheetah.service.GroupService;
import com.cheetah.service.MessageService;
import com.cheetah.util.MapStructMapper;
import com.cheetah.vo.GroupVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

/**
 * @Author chris hoo
 * @Date 2020/8/21
 * @Version V1.0
 * @Description:
 **/
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private MapStructMapper mapStructMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private GroupDAO groupDao;

    @Autowired
    private MessageService messageService;

    /**
     * 创建会话组<br>
     *     创建群组
     *     添加用户群组列表
     *     添加用户到群组成员
     *     发送邀请信息
     *     添加群组-消息关联表
     * @param groupVO
     * @param networkId
     * @return
     */
    @Override
    public GroupDTO createGroup(GroupVO groupVO, String networkId){
        Long id = getGroupId();

        Optional.ofNullable(id).orElseThrow(() -> new CheetahRuntimeException(ServerError.ERROR_CODE_100101));

        Group group = mapStructMapper.groupVo2Group(groupVO);

        groupDao.createGroup(group);

        groupDao.addUserGroupList(groupVO.getCreator(),id.toString(),networkId);

        groupDao.addGroupUser(groupVO.getUserIds(),String.valueOf(id));

        Message message = messageService.sendGroupUserInviteMessage(groupVO.getUserIds(),String.valueOf(id));

        groupDao.addGroupMessage(group.getId(),message);

        GroupDTO groupDTO = mapStructMapper.group2GroupDTO(group);
        //TODO 增加群组头像处理逻辑
        groupDTO.setImage("");
        return groupDTO;
    }

    private Long getGroupId() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("cheetah-id-generator");
        String url = serviceInstance.getUri() + "/id/generator/group/100";
        return restTemplate.postForObject(url,null,Long.class);
    }


}
